﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Core.Business;
using System.Globalization;

namespace TicketManagement.Account
{
    public partial class Profile : System.Web.UI.Page
    {
        private AccountBus bus = new AccountBus();
        private UserBus userBus = new UserBus();
        private Core.Entity.Account acc = new Core.Entity.Account();
        private Core.Entity.User user = new Core.Entity.User();
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                int id = int.Parse(Session["User"].ToString());
                acc = bus.getAccountByUserId(id);
                user = userBus.get(acc.UserId);
            }
            catch (Exception ex) { }
            if (!IsPostBack)
            {
                this.loadAccountType();
                this.loadBank();
                this.loadCountry();
                this.loadCity(acc.CountryId);
                this.loadData();
            }
        }

        public void loadData()
        {
            if (acc.Id > 0)
            {
                lblAccountCode.InnerText = acc.Code;
                rbtActive.Checked = user.IsActive;
                rbtNotActive.Checked = !user.IsActive;
                ddlAccountType.SelectedValue = acc.AccountTypeId.ToString();

                txtRealName.Value = acc.OwnerName;
                txtDelegateName.Value = acc.DelegateName;
                ddlCountry.SelectedValue = acc.CountryId.ToString();
                ddlCity.SelectedValue = acc.CityId.ToString();
                txtAddress.Value = acc.Address;
                txtEmail.Value = user.Email;
                txtTempEmail.Value = acc.AlternateEmail;
                txtCellPhone.Value = acc.CellPhone;
                txtHomePhone.Value = acc.HomePhone;
                txtFax.Value = acc.FaxNumber;
                txtTaxNumber.Value = acc.TaxCode;
                txtIdNumber.Value = acc.IdNumber;
                txtBirthday.Value = acc.BirthDay.ToString("dd/MM/yyyy");
                txtWebsite.Value = acc.HomePage;

                ddlBank.SelectedValue = acc.BankId.ToString();
                txtBankAccountNumber.Value = acc.BankAccountNumber;
                if (acc.IdFrontSide != "") {
                    lblFrontImage.InnerHtml = "<img src='/Assets/data/" + acc.IdFrontSide + "' alt='' width='100px'/>";
                }

                if (acc.IdBackSide != "")
                {
                    lblBackImage.InnerHtml = "<img src='/Assets/data/" + acc.IdBackSide + "' alt='' width='100px'/>";
                }
                
            }
        }

        public void loadAccountType() {
            AccountTypeBus typeBus = new AccountTypeBus();
            List<Core.Entity.AccountType> types = typeBus.getAll();
            ddlAccountType.DataSource = types;
            ddlAccountType.DataBind();
        }

        public void loadBank()
        {
            BankBus bankBus = new BankBus();
            List<Core.Entity.Bank> banks = bankBus.getAll();
            ddlBank.DataSource = banks;
            ddlBank.DataBind();
        }

        public void loadCountry()
        {
            CountryBus countryBus = new CountryBus();
            List<Core.Entity.Country> countries = countryBus.getAll();
            ddlCountry.DataSource = countries;
            ddlCountry.DataBind();
        }

        public void loadCity(int countryId)
        {
            CityBus cityBus = new CityBus();
            List<Core.Entity.City> cities = cityBus.getAll(countryId);
            ddlCity.DataSource = cities;
            ddlCity.DataBind();
        }

        public void update() {

            if (txtPassword.Value != "")
            {
                user.Password = txtNewPassword.Value.Trim();
            }
            user.Email = txtEmail.Value;
            user.IsActive = rbtActive.Checked;

            // Staff
            acc.OwnerName = txtRealName.Value.Trim();
            acc.CountryId = int.Parse(ddlCountry.SelectedValue);
            acc.CityId = int.Parse(ddlCity.SelectedValue);
            acc.Address = txtAddress.Value;
            acc.AlternateEmail = txtTempEmail.Value;
            acc.CellPhone = txtCellPhone.Value;
            acc.HomePhone = txtHomePhone.Value;
            acc.FaxNumber = txtFax.Value;
            acc.TaxCode = txtTaxNumber.Value;
            acc.BankAccountNumber = txtBankAccountNumber.Value;
            if (txtScan1.FileName != "" )
            {
                acc.IdFrontSide = this.saveFrontSide(acc.Code);
            }

            if(txtScan2.FileName != "") 
            {
                acc.IdBackSide = this.saveBackSide(acc.Code);
            }

            try
            {
                DateTime birthday = DateTime.ParseExact(txtBirthday.Value, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                acc.BirthDay = birthday;
            }
            catch (Exception ex) { }

            acc.HomePage = txtWebsite.Value.Trim();
            acc.BankId = int.Parse(ddlBank.SelectedValue);
            
            if (userBus.update(user) && bus.update(acc))
            {
                String script = "alert('Cập nhật thành công!');";
                ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", script, true);
            }
            else
            {
                lblMessage.InnerText = "Không cập nhật được. Vui lòng kiểm tra lại dữ liệu nhập vào";
            }
        }

        private String saveFrontSide(String ticketNumber)
        {
            String fileName = "";
            HttpPostedFile file = txtScan1.PostedFile;
            if (file != null && file.FileName != "")
            {
                try
                {
                    String imageName = ticketNumber + "_" + file.FileName;
                    file.SaveAs(Server.MapPath("/Assets/data/" + imageName));
                    fileName = imageName;
                }
                catch (Exception ex) { }
            }
            return fileName;
        }

        private String saveBackSide(String ticketNumber)
        {
            String fileName = "";
            HttpPostedFile file = txtScan2.PostedFile;
            if (file != null && file.FileName != "")
            {
                try
                {
                    String imageName = ticketNumber + "_" + file.FileName;
                    file.SaveAs(Server.MapPath("/Assets/data/" + imageName));
                    fileName = imageName;
                }
                catch (Exception ex) { }
            }
            return fileName;
        }

        public bool validate()
        {
            //bool isValid = true;

            if (acc.Id > 0)
            {
                // Edit
                if (txtPassword.Value != "")
                {
                    if (txtPassword.Value != user.Password)
                    {
                        correctPasswordValidator.IsValid = false;
                        return false;
                    }

                    if (txtNewPassword.Value == "")
                    {
                        requireNewPassword.IsValid = false;
                        return false;
                    }
                }
            }

            if (txtEmail.Value != user.Email)
            {
                if (userBus.isEmailExist(txtEmail.Value))
                {
                    exitsEmail.IsValid = false;
                    return false;
                }
            }

            if (txtTempEmail.Value != acc.AlternateEmail)
            {
                if (userBus.isEmailExist(txtTempEmail.Value))
                {
                    exitsTempEmail.IsValid = false;
                    return false;
                }
            }

            return true;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (validate())
            {
                this.update();
            }
        }

        protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            int countryId = int.Parse(ddlCountry.SelectedValue);
            loadCity(countryId);
        }
    }
}